<?php
/**
 * @author cattaka.net
 */

require_once 'bootstrap.inc.php';


$params = array_merge($_GET,$_POST);
if (!isset($params["id"])) {
	die('パラメータ"id"が無いよー');
}
//if (!isset($params["target"])) {
//	die('パラメータ"target"が無いよー');
//}
$id = $params["id"];
$target = $params["target"];

$dbh = NULL;
if ($dbh == NULL) {
	$dbh = new PDO($databaseDsn, NULL, NULL);
	$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} else {
	throw new Exception(MSG_DB_ALREADY_CONNECTED);
}

if (isset($target)) {
$couple = null;
	if ($stmt = $dbh->prepare("INSERT INTO COUPLE(ID,TARGET) VALUES (?,?)")) {
		try {
			if ($stmt->execute(array($id,$target))) {
				// OK
				$couple = array("id" => $id, "target" => $target);
			} else {
				// 既に登録してるよー
			}
		} catch (PDOException $e) {
			// 既に登録してるよー
		}
	} else {
		die("Execute sql failed.");
	}
}

$sql = 
"select
	M.ID ID,
	M.NAME NAME,
	C.TARGET TARGET
FROM MEMBERS M
LEFT JOIN (
	SELECT ID, TARGET FROM COUPLE WHERE ID = ?
	UNION ALL
	SELECT TARGET, ID FROM COUPLE WHERE TARGET = ?
) C ON M.ID = C.TARGET
ORDER BY M.ID
";

$coupleList=array();
if ($stmt = $dbh->prepare($sql)) {
	if ($stmt->execute(array($id,$id))) {
		while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
			$member = array("id"=>$row["ID"], "name"=>$row["NAME"]);
			if ($row['TARGET'] == null) {
				$member['known'] = 0; 
			} else {
				$member['known'] = 1; 
			}
			$coupleList[] = $member;
		}
	}
	$stmt->closeCursor();
} else {
	die("Execute sql failed.");
}

?>